package cn.wolfcode.rbac.web.advice;

import cn.wolfcode.rbac.ex.BusinessException;
import cn.wolfcode.rbac.util.R;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.nio.file.AccessDeniedException;

/**
 * 控制器的统一异常处理
 */
@ControllerAdvice
public class MyControllerAdvice {
    /**
     *  @ExceptionHandler 需要定义需要处理什么样的异常
     * @param e
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseBody //出现异常的时候，返回的是JSON字符串，而非页面视图
    public R handleProjectException(BusinessException e){
        e.printStackTrace();
        return R.fail(e.getMessage());
    }
    @ExceptionHandler(Exception.class)
    @ResponseBody //出现异常的时候，返回的是JSON字符串，而非页面视图
    public R handleDefaultException(Exception e){
        e.printStackTrace();
        return R.fail("系统繁忙,稍后再试");
    }
    // 权限
    @ExceptionHandler(AccessDeniedException.class)
    @ResponseBody
    public R handleException(AccessDeniedException exception){
        exception.printStackTrace();
        return R.fail(HttpStatus.FORBIDDEN.value(), "没有权限访问");
    }
    // 认证
    @ExceptionHandler(BadCredentialsException.class)
    @ResponseBody
    public R handleException(BadCredentialsException exception){
        exception.printStackTrace();
        return R.fail(HttpStatus.FORBIDDEN.value(), "账号或者密码错误");
    }
}
